package com.czy.owner.ui.order.frament;

import android.content.Intent;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.czy.owner.R;
import com.czy.owner.adapter.SelectBespokeAdapter;
import com.czy.owner.api.OrderSelectBespokeSelectApi;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.BaseCurrencyListModel;
import com.czy.owner.entity.MyOrderModel;
import com.czy.owner.entity.OrdersListModel;
import com.czy.owner.entity.PackageSelectModel;
import com.czy.owner.entity.SelectBespokeListModel;
import com.czy.owner.entity.WebViewRequestParam;
import com.czy.owner.global.Constants;
import com.czy.owner.net.api.BaseResultEntity;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.ui.BaseFragment;
import com.czy.owner.ui.WebViewActivity;
import com.czy.owner.ui.order.ProjectDetailsWebviewActivity;
import com.czy.owner.ui.workorder.OrderDetailActivity2;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.easyrecycleview.EasyRecyclerView;
import com.easyrecycleview.adapter.RecyclerArrayAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

import static com.czy.owner.entity.WebViewRequestParam.REQUEST_GET;
import static com.czy.owner.entity.WebViewRequestParam.REQUEST_POST;

/**
 * Created by wangyang on 2016/7/8 0008.
 * 全部订单
 */
public class SelectBespokeFragment extends BaseFragment implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.recyclerView)
    EasyRecyclerView recyclerView;
    private SelectBespokeAdapter adapter;
    private int page = 1;
    private Handler handler = new Handler();
    private String session = "";
    private List<SelectBespokeListModel> dataList = new ArrayList<>();
    public static String unPaidDepositTime = "";
    private List<SelectBespokeListModel> selectList = new ArrayList<>();

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_base_subcribeorder;
    }

    @Override
    protected void initInjector() {
        if (getActivity().getIntent().getSerializableExtra("bespoke") != null)
            selectList = (List<SelectBespokeListModel>) getActivity().getIntent().getSerializableExtra("bespoke");

    }

    public void setSelectedData(List<SelectBespokeListModel> datalist) {
        selectList.clear();
        selectList.addAll(datalist);
        adapter.setSelectedList(selectList);
        adapter.notifyDataSetChanged();
    }

    public void selectStore() {
        dataList.clear();
        selectList.clear();
        adapter.setSelectedList(selectList);
        adapter.clear();
        adapter.notifyDataSetChanged();
        recyclerView.showProgress();
//        recyclerView.getSwipeToRefresh().setRefreshing(true);
        onRefresh();
    }

    @Override
    protected void initViews() {
        init();
    }

    @Override
    protected void updateViews() {

        onRefresh();
    }

    public List<SelectBespokeListModel> getSelectedList() {
        return adapter.getSelectedList();
    }

    private void init() {

        session = UserHelper.getInstance().getSessionInfoModel(getActivity()).getSession();
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapterWithProgress(adapter = new SelectBespokeAdapter(getActivity()));
//        recyclerView.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.VERTICAL, R.drawable.shape_order_fragment_recyclerview_divider_decoration));
        recyclerView.setEmptyView(R.layout.view_empty_common);
        recyclerView.setErrorView(R.layout.view_error_refresh);
        adapter.setMore(R.layout.view_more, this);
        adapter.setNoMore(R.layout.view_nomore);
        adapter.setSelectedList(selectList);
        adapter.addAll(dataList);

        recyclerView.setRefreshListener(this);
        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener<SelectBespokeListModel>() {
            @Override
            public void onItemClick(View view, int position, SelectBespokeListModel model) {
                WebViewRequestParam webViewRequestParam = new WebViewRequestParam(Constants.APP_API_BASE + "/own/order/serviceInfo");
                webViewRequestParam.setRequestMethod(REQUEST_POST);
                webViewRequestParam.setParams("session=" + UserHelper.getInstance().getSessionInfoModel(
                        getActivity()).getSession() + "&storeId=" + (SharedPreferencesUtils.getParam(getActivity(), UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "") + "&storeServiceId="
                        + model.getStoreServiceId());
                webViewRequestParam.setTitle("服务详情");
                Intent intent = new Intent(getActivity(), ProjectDetailsWebviewActivity.class);
                intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, webViewRequestParam);
                startActivity(intent);


            }
        });

    }

    @Override
    public void onLoadMore() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新
                if (!PhoneUtils.isNetworkConnected(getActivity())) {
                    adapter.pauseMore();
                    recyclerView.showError();
                    return;
                }
                page++;
                getDataList(false);

            }
        }, 1000);
    }


    @Override
    public void onRefresh() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新
                if (!PhoneUtils.isNetworkConnected(getActivity())) {
                    adapter.pauseMore();
                    recyclerView.showError();
                    return;
                }
                page = 1;
                getDataList(true);
            }
        }, 1000);
    }

    //获取项目服务
    private void getDataList(final boolean isFirst) {
        OrderSelectBespokeSelectApi orderListApi = new OrderSelectBespokeSelectApi(new HttpOnNextListener<BaseCurrencyListModel<SelectBespokeListModel>>() {
            @Override
            public void onNext(BaseCurrencyListModel<SelectBespokeListModel> model) {
                if (isFirst)
                    adapter.clear();
                setDataList(model);
            }

            @Override
            public void onCacheNext(String cache) {
                super.onCacheNext(cache);
                Gson gson = new Gson();
                Type type = new TypeToken<BaseResultEntity<OrdersListModel>>() {
                }.getType();
                BaseResultEntity<OrdersListModel> model = gson.fromJson(cache, type);

            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(getActivity(), e.getMessage());
            }


        }, (RxAppCompatActivity) (getActivity()));
        if(UserHelper.getInstance().getSessionInfoModel(getActivity()) != null) {
            orderListApi.setSession(UserHelper.getInstance().getSessionInfoModel(getActivity()).getSession());
        }
        orderListApi.setStoreId(SharedPreferencesUtils.getParam(getActivity(), UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
        orderListApi.setPage(page + "");
        orderListApi.setSize("50");
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(orderListApi);
    }

    //填充数据
    private void setDataList(BaseCurrencyListModel<SelectBespokeListModel> model) {
        if (model.getList().size() < 50) {
            adapter.stopMore();
        }
        adapter.addAll(model.getList());
        if (adapter.getAllData().size() == 0) {
            recyclerView.setEmptyView(R.layout.view_empty_common);
            recyclerView.showEmpty();
        }
    }

    @Override
    public void reloadData() {
        //刷新
        if (!PhoneUtils.isNetworkConnected(getActivity())) {
            if (adapter != null)
                adapter.pauseMore();
            return;
        }
        page = 1;
        getDataList(true);
    }
}